package com.campusbook.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

/**
 * 数据库配置类
 * 演示Environment抽象用于配置管理
 */
@Configuration
@MapperScan(basePackages = "com.campusbook.dao")
@EnableTransactionManagement
public class DatabaseConfig {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);
    
    @Autowired
    private Environment environment;

    /**
     * 数据源配置，使用Environment获取配置属性
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        
        // 使用Environment抽象获取配置
        dataSource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
        dataSource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
        dataSource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
        dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name", "com.mysql.cj.jdbc.Driver"));
        
        // 连接池配置
        dataSource.setInitialSize(environment.getProperty("spring.datasource.initial-size", Integer.class, 5));
        dataSource.setMaxActive(environment.getProperty("spring.datasource.max-active", Integer.class, 20));
        dataSource.setMinIdle(environment.getProperty("spring.datasource.min-idle", Integer.class, 5));
        
        logger.info("数据源配置完成: {}", dataSource.getUrl());
        return dataSource;
    }

    /**
     * MyBatis SqlSessionFactory配置
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        
        // 使用Resource加载MyBatis配置文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:mapper/*.xml");
        sessionFactory.setMapperLocations(resources);
        
        // 设置别名包
        sessionFactory.setTypeAliasesPackage("com.campusbook.model");
        
        logger.info("MyBatis配置完成，找到{}个mapper文件", resources.length);
        return sessionFactory;
    }

    /**
     * 事务管理器
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
